package com.example.bourse.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.example.bourse.core.result.ApiResult;
import com.example.bourse.pojo.bo.RoleBo;
import com.example.bourse.pojo.entity.Role;
import com.example.bourse.pojo.entity.Menu;
import com.example.bourse.pojo.entity.AdminUser;
import com.example.bourse.pojo.entity.Activity;
import com.example.bourse.pojo.dto.RoleDto;
import com.example.bourse.service.RoleService;
import com.example.bourse.service.AdminUserService;
import com.example.bourse.core.result.PageResult;
import com.example.bourse.core.utils.PageUtils;
import org.noear.solon.annotation.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;

import java.util.Date;
import java.util.List;

@Controller
@Mapping("/admin")
@Deprecated
public class AdminController {
    // 该类已废弃，请使用新的分拆后的Controller

    @Inject
    private AdminUserService adminUserService;

    @Get
    @Mapping("/dashboard/user-count")
    public String getUserCount() {
        long count = adminUserService.getUserCount();
        return String.valueOf(count);
    }

    @Get
    @Mapping("/dashboard/today-user-count")
    public String getTodayUserCount() {
        long count = adminUserService.getTodayUserCount();
        return String.valueOf(count);
    }

    @Get
    @Mapping("/dashboard/pending-order-count")
    public String getPendingOrderCount() {
        long count = adminUserService.getPendingOrderCount();
        return String.valueOf(count);
    }

    @Get
    @Mapping("/dashboard/system-message-count")
    public String getSystemMessageCount() {
        long count = adminUserService.getSystemMessageCount();
        return String.valueOf(count);
    }

    @Get
    @Mapping("/dashboard/recent-activities")
    public String getRecentActivities() {
        List<Activity> activities = adminUserService.getRecentActivities();
        return renderActivitiesTable(activities);
    }

    private String renderActivitiesTable(List<Activity> activities) {
        StringBuilder sb = new StringBuilder();
        sb.append("<tbody>");
        for (Activity activity : activities) {
            sb.append("<tr>")
              .append("<td>").append(activity.getTime()).append("</td>")
              .append("<td>").append(activity.getAction()).append("</td>")
              .append("<td>").append(activity.getUsername()).append("</td>")
              .append("<td>").append(activity.getDetails()).append("</td>")
              .append("</tr>");
        }
        sb.append("</tbody>");
        return sb.toString();
    }

    @Inject
    private RoleService roleService;

    /**
     * 新增管理员
     * @param username 用户名
     * @param password 密码
     * @param nickname 昵称
     * @return 操作结果
     */
    @Post
    @Mapping("/add")
    public ApiResult addAdmin(
            @Param String username,
            @Param String password,
            @Param String nickname) {
        AdminUser admin = new AdminUser();
        admin.setUsername(username);
        admin.setPassword(DigestUtils.md5Hex(password));
        admin.setNickname(nickname);
        admin.setStatus(1);
        admin.setDelFlag(0);
        admin.setCreateDate(new Date());
        admin.setUpdateDate(new Date());
        
        adminUserService.addUser(admin);
        return ApiResult.success();
    }

    @Mapping("/index")
    public ModelAndView index(Context ctx) {
        ModelAndView vm = new ModelAndView("admin/layout.html");
        
        // 获取统计数据
        long userCount = adminUserService.getUserCount();
        int roleCount = adminUserService.getRoleCount();
        int menuCount = adminUserService.getMenuCount();
        long todayUserCount = adminUserService.getTodayUserCount();
        long pendingOrderCount = adminUserService.getPendingOrderCount();
        long systemMessageCount = adminUserService.getSystemMessageCount();
        List<Activity> recentActivities = adminUserService.getRecentActivities();
        
        // 设置模板变量
        vm.put("userCount", userCount);
        vm.put("roleCount", roleCount);
        vm.put("menuCount", menuCount);
        vm.put("todayUserCount", todayUserCount);
        vm.put("pendingOrderCount", pendingOrderCount);
        vm.put("systemMessageCount", systemMessageCount);
        vm.put("recentActivities", recentActivities);
        
        return vm;
    }

    @Post
    @Mapping("/login")
    public ApiResult login(String username, String password) {
        AdminUser user = adminUserService.login(username, password);
        if (user == null) {
            return ApiResult.fail("用户名或密码错误");
        }
        StpUtil.login(user.getId());
        return ApiResult.success("登录成功");
    }

    @SaCheckLogin
    @Mapping("/info")
    public ApiResult getUserInfo() {
        long userId = StpUtil.getLoginIdAsLong();
        AdminUser user = adminUserService.getUserById(userId);
        if (user == null) {
            return ApiResult.fail("用户不存在");
        }
        return ApiResult.success(user);
    }

    @SaCheckPermission("user:add")
    @Post
    @Mapping("/add")
    public ApiResult addUser(AdminUser user) {
        if (adminUserService.getUserByUsername(user.getUsername()) != null) {
            return ApiResult.fail("用户名已存在");
        }
        adminUserService.addUser(user);
        return ApiResult.success("添加用户成功");
    }

    @Post
    @Mapping("/register")
    public ApiResult register(String username, String password, String confirmPassword) {
        if (!password.equals(confirmPassword)) {
            return ApiResult.fail("两次输入的密码不一致");
        }
        
        AdminUser user = new AdminUser();
        user.setUsername(username);
        user.setPassword(password);
        
        if (adminUserService.getUserByUsername(username) != null) {
            return ApiResult.fail("用户名已存在");
        }
        
        adminUserService.addUser(user);
        return ApiResult.success("注册成功");
    }

    @SaCheckPermission("user:role")
    @Get
    @Mapping("/users/{userId}/roles")
    public ApiResult getUserRoles(@Path("userId") Long userId) {
        List<RoleDto> roles = adminUserService.getUserRoles(userId);
        return ApiResult.success(roles);
    }

    @SaCheckPermission("user:role")
    @Put
    @Mapping("/users/{userId}/roles")
    public ApiResult saveUserRoles(@Path("userId") Long userId, @Body RoleBo request) {
        adminUserService.saveUserRoles(userId, request.getRoles());
        return ApiResult.success("角色分配成功");
    }

    @SaCheckPermission("user:list")
    @Get
    @Mapping("/users")
    public Object getUsers(Context ctx,
                         @Param(defaultValue = "1") int page,
                         @Param(defaultValue = "") String username) {
        PageResult<AdminUser> userPage = adminUserService.listUsers(page, username);
        
        if (ctx.header("HX-Request") != null) {
            // HTMX请求，返回局部视图
            ModelAndView vm = new ModelAndView("admin/users::userTableBody");
            vm.put("users", userPage.getContent());
            vm.put("currentPage", page);
            vm.put("totalPages", userPage.getTotalPages());
            return vm;
        }
        
        // 完整页面请求
        ModelAndView vm = new ModelAndView("admin/users");
        vm.put("users", userPage.getContent());
        vm.put("currentPage", page);
        vm.put("totalPages", userPage.getTotalPages());
        return vm;
    }

    @SaCheckPermission("user:list")
    @Get
    @Mapping("/users/{userId}/roles")
    public Object getUserRoles(Context ctx, @Path("userId") Long userId) {
        List<RoleDto> roles = adminUserService.getUserRoles(userId);
        
        if (ctx.header("HX-Request") != null) {
            ModelAndView vm = new ModelAndView("admin/users::roleModalContent");
            vm.put("roles", roles);
            vm.put("userId", userId);
            return vm;
        }
        
        return ApiResult.success(roles);
    }

    @SaCheckPermission("user:edit")
    @Put
    @Mapping("/users/{id}")
    public ApiResult updateUser(@Path("id") Long id, @Body AdminUser user) {
        user.setId(id);
        adminUserService.updateUser(user);
        return ApiResult.success("用户信息更新成功");
    }

    @SaCheckPermission("user:delete")
    @Post
    @Mapping("/users/{id}/delete")
    public ApiResult deleteUser(@Path("id") Long id) {
        adminUserService.deleteUser(id);
        return ApiResult.success("用户删除成功");
    }

    @Get
    @Mapping("/menus")
    public String menus() {
        return "admin/menus";
    }

    @Get
    @Mapping("/roles")
    public Object roles(Context ctx,
                      @Param(defaultValue = "1") int page,
                      @Param(defaultValue = "") String roleName) {
        PageResult<Role> rolePage = roleService.listRoles(page, roleName);
        
        if (ctx.header("HX-Request") != null) {
            ModelAndView vm = new ModelAndView("admin/roles::roleTableBody");
            vm.put("roles", rolePage.getContent());
            vm.put("currentPage", page);
            vm.put("totalPages", rolePage.getTotalPages());
            return vm;
        }
        
        ModelAndView vm = new ModelAndView("admin/roles");
        vm.put("roles", rolePage.getContent());
        vm.put("currentPage", page);
        vm.put("totalPages", rolePage.getTotalPages());
        return vm;
    }

    @SaCheckPermission("role:add")
    @Post
    @Mapping("/roles")
    public ApiResult addRole(@Body Role role) {
        roleService.addRole(role);
        return ApiResult.success("角色添加成功");
    }

    @SaCheckPermission("role:edit")
    @Put
    @Mapping("/roles/{id}")
    public ApiResult updateRole(@Path("id") Long id, @Body Role role) {
        role.setId(id);
        roleService.updateRole(role);
        return ApiResult.success("角色更新成功");
    }

    @SaCheckPermission("role:delete")
    @Post
    @Mapping("/roles/{id}/delete")
    public ApiResult deleteRole(@Path("id") Long id) {
        roleService.deleteRole(id);
        return ApiResult.success("角色删除成功");
    }

    @SaCheckPermission("role:menu")
    @Get
    @Mapping("/roles/{roleId}/menus")
    public ApiResult getRoleMenus(@Path("roleId") Long roleId) {
        List<Menu> menus = roleService.getRoleMenus(roleId);
        return ApiResult.success(menus);
    }

    @SaCheckPermission("role:menu")
    @Put
    @Mapping("/roles/{roleId}/menus")
    public ApiResult saveRoleMenus(@Path("roleId") Long roleId, @Body List<Long> menuIds) {
        roleService.saveRoleMenus(roleId, menuIds);
        return ApiResult.success("菜单权限保存成功");
    }
}
